package exabase.com;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Logger;

import org.junit.Before;
import org.junit.Test;

import exabase.Exabase;
import exabase.com.dataTransfer.DataTransfer;

public class ComTest {
	private static Logger logger = Logger.getLogger(ComTest.class.getName());

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testCom() {
		Exabase.getInstance().go();
		String host = "localhost";
		for (int i = 0; i < 5; i++)
			testConnect(host, i);
	}

	protected void testConnect(String host, int rep) {
		try {
			Socket socket = new Socket(host, 8386);

			InetAddress localAddress = socket.getLocalAddress();

			logger.fine("Connecting from local address  " + localAddress);

			DataTransfer dataTransfer = new DataTransfer(socket);
			for (int i = 0; i < rep + 1; i++) {
				int result = dataTransfer.ping(rep);
				Thread.sleep(2);
				assertEquals("data should be transmitted ok", rep, Com
						.getInstance().getPingResult());
				assertEquals("data should be transmitted ok", rep, result);
			}
			dataTransfer.disconnect();
		} catch (Exception ex) {
			fail(ex.toString());
		}
	}

}
